<!--分配用户角色-->
<template>
  <div class="userRoles">
    <el-dialog
      title="分配角色"
      :visible.sync="dialogVisible"
      width="35%"
      :before-close="dialogClose">
      <el-select v-model="roleIdList" multiple placeholder="请选择">
        <el-option
          v-for="item in roleAll"
          :key="item.id"
          :label="item.name"
          :value="item.id">
        </el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogClose" size="small">取 消</el-button>
        <el-button type="primary" size="small" @click="OnSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getRoleAll, getUserRole } from '@/services/role'
import { allocateUserRoles } from '@/services/users'

export default {
  name: 'allocRole',
  data () {
    return {
      dialogVisible: false,
      roleAll: [],
      roleIdList: [],
      roleId: ''
    }
  },
  created () {
    this.getRoleAll()
  },
  methods: {
    dialogClose () {
      this.dialogVisible = false
    },
    // 打开弹窗,并通过list组件传递过来的id值,并渲染数据
    async dialogOpen (id) {
      this.dialogVisible = true
      // 存储当前的用户 id值
      this.roleId = id
      const { data } = await getUserRole(id)
      if (data.code === '000000') {
        // 将请求来的数组中的数据通过map()筛选出id,添加到roleIdList,组成新的数组
        this.roleIdList = data.data.map(item => item.id)
      }
    },
    // 获取所有的角色列表
    async getRoleAll () {
      const { data } = await getRoleAll()
      if (data.code === '000000') {
        this.roleAll = data.data
      }
    },
    // 提交新的分配角色
    async OnSubmit () {
      const obj = {
        userId: this.roleId,
        roleIdList: this.roleIdList
      }
      const { data } = await allocateUserRoles(obj)
      if (data.code === '000000') {
        this.$message.success('保存成功')
      }
      this.dialogClose()
    }
  }
}
</script>

<style lang="scss" scoped>
.el-input__inner{
  width: 260px;
}
</style>
